package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"runtime"
	//	"syscall"
	//"github.com/miolini/godaemon"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strconv"
	"time"
)

func PrintLog(logcontent string, t2 int) {
	var logtime = time.Now().Format("20060102")
	var logFileName = "daemon." + logtime + ".log"
	runtime.GOMAXPROCS(runtime.NumCPU())
	logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("can't write log!")
		return
	}
	defer logFile.Close()
	if t2 == 1 {
		gLogger := log.New(logFile, "", log.Ldate|log.Ltime)
		gLogger.Printf("   %v\n", logcontent)
	} else {
		gLogger1 := log.New(logFile, "", 0)
		gLogger1.Printf("   %v\n", logcontent)
	}

}

func work() {
	for {
		PrintLog("daemon test", 1)
		time.Sleep(1 * time.Second)
	}
}

func startprocess(pidpath, args string) (pid int, err error) {
	if _, err := os.Stat(pidpath); err != nil {
		if os.Getppid() != 1 {
			//fmt.Printf("%d", os.Getpid())
			filePath, _ := filepath.Abs(os.Args[0])
			cmd := exec.Command(filePath, args)
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			cmd.Start()
			fmt.Println("[PID]", cmd.Process.Pid)
			err = ioutil.WriteFile(pidpath, []byte(strconv.Itoa(cmd.Process.Pid)), 0640)
			//return
		}
	} else {
		fmt.Println("xmonitor already running")
		//return
	}
	return
}

func stopprocess(pidpath string) {
	fi, err := os.Open(pidpath)
	if err != nil {
		//panic(err)
		fmt.Println(err.Error())
	}
	defer fi.Close()
	fd, err := ioutil.ReadAll(fi)
	fmt.Println(string(fd))
	cmd := exec.Command("kill", string(fd))
	cmd.Start()
	err = os.Remove(pidpath)
	if err != nil {
		fmt.Println("delete failure!")
	}
	return
}

func main() {
	runwork := flag.Bool("r", false, "run in daemon mode")
	daemon := flag.Bool("d", false, "run in daemon mode")
	stoppid := flag.Bool("stop", false, "run in daemon mode")
	flag.Parse()
	if *runwork {
		work()
	}
	if *daemon {
		startprocess("mydaemon.pid", "-r=true")
	}

	if *stoppid {
		stopprocess("mydaemon.pid")
	}
}
